package com.springboot.demo.exception;

import com.springboot.demo.utils.ResponseResult;
import com.springboot.demo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;


/**
 * @author wubc683
 * @desc 统一异常处理器
 * @date 2021-08-09 17:31
 */
@RestControllerAdvice("com.springboot.demo")
@Slf4j
public class GlobalExceptionHandler {
    @Autowired
    ResponseUtils responseUtils;

    /**
     * 未知错误异常
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseUtils<String> exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("系统异常,url={},method={}",request.getRequestURL(), request.getMethod(),e);
        return responseUtils.buildFailedResponse(ResponseResult.SYSTEM_ERROR,e.getMessage());
    }

    /**
     * 非预期的运行时异常
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseUtils runtimeExceptionHandler(HttpServletRequest request, RuntimeException e) {
        log.error("运行时异常,url={},method={}",request.getRequestURL(), request.getMethod(),e);

        return new ResponseUtils(ResponseResult.INTERNAL_SERVER_ERROR,e.getMessage());
    }

    /**
     * 业务异常
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseUtils businessExceptionHandler(HttpServletRequest request, BusinessException e) {
        log.error("业务异常,url={},method={}", request.getRequestURL(), request.getMethod(), e);
        return responseUtils.buildFailedResponse(e.getCode(),e.getMessage());
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseUtils BindExceptionHandler(HttpServletRequest request, BindException e) {
        log.error("请求参数异常,url={},{}", request.getRequestURL(), request.getMethod(), e);
        return responseUtils.buildFailedResponse(ResponseResult.BAD_REQUEST.getCode(),
                e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.toList()).get(0));
    }

    /**
     * 错误页面异常 统一处理
     * @param e
     * @return: Result
     */
    @ExceptionHandler(value = ErrorPageException.class)
    public ResponseUtils errorPageExceptionHandler(ErrorPageException e){
        //把错误信息输入到日志中
        log.error("页面错误，code={},message={}", e.getCode(),e.getMessage());
        return responseUtils.buildFailedResponse(e.getCode(),e.getMessage());
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseUtils constraintViolationExceptionHandler(HttpServletRequest request, ConstraintViolationException e) {
        log.error("请求参数异常,url={},{}", request.getRequestURL(), request.getMethod(), e);
        return responseUtils.buildFailedResponse(ResponseResult.BAD_REQUEST.getCode(),
                e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()).get(0),
        null);
    }

    /**
     * 处理请求参数格式错误 @RequestParam上参数转换失败后抛出的异常
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseUtils methodArgumentTypeMismatchExceptionHandler(HttpServletRequest request,
                                                                    MethodArgumentTypeMismatchException e) {
        log.error("请求参数异常,url={},{}", request.getRequestURL(), request.getMethod(), e);
        return responseUtils.buildFailedResponse(ResponseResult.BAD_REQUEST.getCode(), "参数类型不匹配");
    }

    /**
     * 处理请求参数格式错误 @RequestBody上validate失败后抛出的异常
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseUtils methodArgumentNotValidExceptionHandler(HttpServletRequest request,
                                                          MethodArgumentNotValidException e) {
        log.error("请求参数异常,url={},{}", request.getRequestURL(), request.getMethod(), e);
        return new ResponseUtils(ResponseResult.BAD_REQUEST.getCode(),
                e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.toList()).get(0),
                null);
    }

    /**
     * 处理请求参数格式错误 @RequestBody参数转换错误
     * @param request
     * @param e
     * @return: com.springboot.demo.utils.ResponseUtils
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseUtils httpMessageNotReadableExceptionHandler(HttpServletRequest request,
                                                          HttpMessageNotReadableException e) {
        log.error("请求参数异常,url={},{}", request.getRequestURL(), request.getMethod(), e);
        return new ResponseUtils(ResponseResult.BAD_REQUEST.getCode(), "请求体参数转换错误", null);
    }

//    /**
//     * 405 - Method Not Allowed
//     * @param request
//     * @param e
//     * @return: com.springboot.demo.utils.ResponseUtils
//     */
//    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
//    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
//    public ResponseUtils handleHttpRequestMethodNotSupportedExceptionHandler(HttpServletRequest request,
//                                                                      HttpRequestMethodNotSupportedException e) {
//        log.error("不支持当前请求方法,url={},{}",request.getRequestURL(),request.getMethod(), e);
//        return new ResponseUtils(HttpStatus.METHOD_NOT_ALLOWED.value(), "请求方法不支持",null);
//    }
}